
declare const api: any;

export default {
    cacheImage(src: string): Promise<string> {
        return new Promise((resolve) => {
            if (src.substr(0, 4) === 'http') {
                api.imageCache({
                    url: src,
                    policy: 'cache_only'
                }, function (ret: any, err: any) {
                    resolve(ret.url)
                });
            } else {
                resolve(src);
            }
        });
    },
    toBase64(path: string): Promise<string> {
        return new Promise((resolve) => {
            if (path.substr(0, 1) === '/') {
                const trans = api.require('trans');
                trans.decodeImgToBase64({
                    imgPath: path
                }, (ret: any, err: any) => {
                    if (ret.status) {
                        resolve(ret.base64Str);
                    } else {
                        resolve('');
                    }
                });
            } else {
                resolve(path);
            }

        });
    },
    toFilePath(base64Str: string, tag: string = Date.now().toString()): Promise<string> {
        return new Promise((resolve) => {
            const imgName = `mk_view_${tag}.png`;
            const imgPath = `${api.cacheDir}/mk_view/`;
            const fullPath = `${imgPath}${imgName}`;
            const fs = api.require('fs');
            const ret = fs.existSync({
                path: fullPath
            });
            if (ret.exist) {
                resolve(fullPath);
                return;
            }
            const trans = api.require('trans');
            trans.saveImage({
                base64Str,
                imgPath,
                imgName
            }, (ret: any, err: any) => {
                if (ret.status) {
                    resolve(fullPath);
                } else {
                    resolve('');
                }
            });
        });
    }
}
